import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document'
import styled, { ServerStyleSheet } from 'styled-components'
import PropTypes from 'prop-types';
import flush from 'styled-jsx/server';

const Body = styled.body`
min-width: 300px;
margin: 0 auto;
background:#fefefe;
`;

export default class MyDocument extends Document {
  static getInitialProps({ renderPage, req, res }) {


    const sheet = new ServerStyleSheet();
    let pageContext;
    const page = renderPage(Component => {
      const WrappedComponent = props => {

        pageContext = props.pageContext;
        return sheet.collectStyles(

          <Component {...props} />
        )
      }

      WrappedComponent.propTypes = {
        pageContext: PropTypes.object.isRequired,
      };

      return WrappedComponent;

    });

    const styleTags = sheet.getStyleElement();

    return {
      ...page, styleTags, res, req, pageContext, styles: (
        <>
          <style
            id="jss-server-side"
            // eslint-disable-next-line react/no-danger
            dangerouslySetInnerHTML={{ __html: pageContext.sheetsRegistry.toString() }}
          />
          {flush() || null}
        </>
      ),
    }
  }


  render() {
    // console.log(this.props.req.path)
    const { pageContext } = this.props;
    return (
      <html lang="zh-CN" dir="ltr">
        <Head>

          <meta charSet="utf-8" />
          {/* Use minimum-scale=1 to enable GPU rasterization */}
          <meta
            name="viewport"
            content={
              'user-scalable=0, initial-scale=1, ' +
              'minimum-scale=1, width=device-width, height=device-height'
            }
          />
          {/* PWA primary color */}
          <meta name="theme-color" content={pageContext.theme.palette.primary.main} />

          {this.props.styleTags}
        </Head>
        <Body>
          <Main />
          <NextScript />
        </Body>
      </html>
    )
  }
}
 

